//
//  MAINViewController.m
//  HaHa
//
//  Created by 元虎的mac on 15/9/24.
//  Copyright (c) 2015年 吉亚平. All rights reserved.
//

#import "MAINViewController.h"

@interface MAINViewController ()
//控件类
@property (nonatomic) UITableView *oneTableView;
@property (nonatomic) UILabel *tiplable;
@property (nonatomic) UIImageView *refreshButton;

//test
@property (nonatomic) NSMutableArray *frames;
//数据类
@property (nonatomic) NSMutableArray *modeArray;
@end

@implementation MAINViewController
{
    NSString *Maxtime; //最大时间
    NSString *MinTime; //最小时间
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = KBackColor;
    self.navigationController.navigationBar.translucent = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self AddSubViews];
    [self AddMJ];
    [self AddTip];
    [self addrefreshButton];
    [self GetNHDZdata];
    [self adtap];
}

- (void)adtap{
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesure)];
    [swipe setDirection:(UISwipeGestureRecognizerDirectionLeft)];
    [self.view addGestureRecognizer:swipe];
}
- (void)animationD{
    CATransition *transition = [CATransition animation];
    //指定动画类型
    transition.type = @"cube";//效果类型
    transition.subtype = kCATransitionFromTop;//方向类型 决定动画的开始方向
    transition.duration = 0.8; //单次动画时长
    [self.tabBarController.tabBar.layer addAnimation:transition forKey:@" 但是"];
}
- (void)swipeGesure{
    [self animationD];
//    [self.tabBarController setSelectedIndex:1];
}
//gifData
- (void)GifData{
    NSMutableArray *images = [[NSMutableArray alloc] init];
    for (int i = 0; i < 22; i++) {
        UIImage *temp = [UIImage imageNamed:[NSString stringWithFormat:@"%d",i+1]];
        [images addObject:temp];
    }
    self.refreshButton.animationImages = images;
}



//刷新数量
- (void)AddTip{
    self.tiplable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenWdth, 20)];
    self.tiplable.backgroundColor = KArcColor;
    self.tiplable.textColor = [UIColor whiteColor];
    self.tiplable.alpha = 0.8;
    self.tiplable.textAlignment = NSTextAlignmentCenter;
    self.tiplable.text = @"好笑的就要来啦";
    [self.view addSubview:self.tiplable];
}
//添加上拉刷新 和下拉加载
- (void)AddMJ{
    __block MAINViewController *root = self;
    [self.oneTableView addHeaderWithCallback:^{
        [root GetNHDZdata];
        [root.oneTableView headerEndRefreshing];
    }];
    [self.oneTableView addFooterWithCallback:^{
        [root GetNHDZMoredata];
        [root.oneTableView footerEndRefreshing];
    }];
}
- (void)AddSubViews{
    self.oneTableView = [[UITableView alloc] initWithFrame:CGRectMake(5, 0,kScreenWdth-10 ,kScreenHeight-113)];
    self.oneTableView.delegate = self;
    self.oneTableView.dataSource = self;
    self.oneTableView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
    [self.view addSubview:self.oneTableView];
}
//刷新按钮
-(void)addrefreshButton{
    UIView *Back = [[UIView alloc] initWithFrame:CGRectMake(kScreenWdth-60, kScreenHeight-163, 40, 40)];
    Back.backgroundColor = [UIColor whiteColor];
    Back.layer.borderWidth = 0.5;
    Back.alpha = 0.8;
    Back.layer.borderColor = [[UIColor brownColor] CGColor];
    Back.layer.cornerRadius = 20;
    
    self.refreshButton = [[UIImageView alloc] initWithFrame:CGRectMake(7.5,7.5 , 25, 25)];
    self.refreshButton.image = [UIImage imageNamed:@"16"];
    self.refreshButton.layer.borderColor = [[UIColor brownColor] CGColor];
    self.refreshButton.userInteractionEnabled = YES;
    [self GifData];
    self.refreshButton.animationDuration = 0.4;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(refreshButtonClick)];
    [self.refreshButton addGestureRecognizer:tap];
    [Back addSubview:self.refreshButton];
    [self.view addSubview:Back];
}

//刷新按钮事件
- (void)refreshButtonClick{
    [self.oneTableView setContentOffset:CGPointMake(0, 0) animated:YES];
    [self GetNHDZdata];
}
#pragma mark - 表视图数据
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return 1;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    static NSString  *identifier = @"cell";
    VideoShowTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[VideoShowTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
    }
    
    HotVideoMode *mode = self.modeArray[indexPath.section];
    [cell setContentForHMode:mode];
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HotVideoMode *mode = self.modeArray[indexPath.section];
    
    //计算标题高度
    CGFloat TitleHeight = [self YYHreturnStringHeight:mode.text Width:kScreenWdth-30 Font:17];
    if (TitleHeight==0) {
        TitleHeight = 21;
    }
    
    CGFloat commentTextHeight;
    if (mode.comments.count == 0) {
    }else{
        NSDictionary *comment = [mode.comments firstObject];
        NSString *CommentText = [comment objectForKey:@"text"];
        commentTextHeight = [self YYHreturnStringHeight:CommentText Width:kScreenWdth-80 Font:17]+80;
//        NSLog(@"%f %@",commentTextHeight,CommentText);

    }
    
    
    //将宽度大于tableview宽度的图片缩放
    NSInteger videoWdith = [mode.video_width integerValue];
    
    //将要返回的视频高度
    CGFloat returnVideoHeight = [mode.video_height integerValue];
    if (videoWdith > _oneTableView.width-20) {
        //计算表视图的宽度与视频宽度的比例
        CGFloat beishu = videoWdith / (_oneTableView.width-20);
        returnVideoHeight = [mode.video_height integerValue] / beishu;
    }
    if (returnVideoHeight == 0) {
        returnVideoHeight = kScreenWdth-30;
    }

    
    return 120 + TitleHeight+commentTextHeight+returnVideoHeight;
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    
    return self.modeArray.count;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    HotVideoMode *mode = self.modeArray[indexPath.section];
    VideoPlayViewController *PlayVC = [[ VideoPlayViewController alloc] init];
    PlayVC.Mode = mode;
    [self.navigationController pushViewController:PlayVC animated:YES];
}

#pragma mark - 内涵段子数据请求
- (void)GetNHDZdata{
    [self.refreshButton startAnimating];
    if (!self.modeArray) {
        self.modeArray = [NSMutableArray array];
    }
    
    //获取当前时间的时间截 从这个时间开始请求最新数据
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    NSInteger b = a*1-600;
    NSString *timeString = [NSString stringWithFormat:@"%ld", b];
    NSString *url = [NSString stringWithFormat:@"%@%@%@",KHot,timeString,KhotB];
    //如果已经请求过了 就用已经请求过的最后的的时间开始请求
    if (MinTime) {
        url = [NSString stringWithFormat:@"%@%@%@",KHot,MinTime,KhotB];
    }
    [LORequestManger GET:url success:^(id response) {
        NSDictionary *Dic = (NSDictionary *)response;
        NSDictionary *dataDic = [Dic objectForKey:@"data"];

        NSArray *dataArray = [dataDic objectForKey:@"data"];
        
        for (NSDictionary *temp in dataArray) {
           Maxtime =  [temp objectForKey:@"display_time"];
            HotVideoMode *mode = [HotVideoMode SetModeWithDIC:temp];
            //已经请求过  后面请求的是最新的 所有把他们插入到数组的最前面
            if (MinTime) {
                [self.modeArray insertObject:mode atIndex:0];
            }else{
                [self.modeArray addObject:mode];
            }
        }
        //获取当前请求的最大时间 和最小时间
        MinTime = [dataDic objectForKey:@"min_time"];
        Maxtime =  [dataDic objectForKey:@"max_time"];
//        NSLog(@"最大时间 %@最小时间%@",Maxtime,MinTime);
        //刷新
        [self.oneTableView reloadData];
        _tiplable.text = [NSString stringWithFormat:@"%ld条新内容",self.modeArray.count];
        //动画
        CATransition *transition = [CATransition animation];
        transition.type = @"cube";//效果类型
        transition.subtype = kCATransitionFromRight;//方向类型 决定动画的开始方向
        transition.duration = 0.4; //单次动画时长
        [self.tiplable.layer addAnimation:transition forKey:@""];
        self.tiplable.hidden = NO;
        [self.refreshButton stopAnimating];
        //延时3秒隐藏tip提示
        [self hiddenTip];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self NetWrokErrorFunc];
    }];
}
//加载更多
- (void)GetNHDZMoredata{
    [self.refreshButton startAnimating];
    //前一次请求最后的一个时间截 作为加载更多是的第一个时间截
    NSString *url = [NSString stringWithFormat:@"%@%@%@",KHotC,Maxtime,KhotD];
    [LORequestManger GET:url success:^(id response) {
        NSDictionary *Dic = (NSDictionary *)response;
        NSDictionary *dataDic = [Dic objectForKey:@"data"];
        
        NSArray *dataArray = [dataDic objectForKey:@"data"];
        for (NSDictionary *temp in dataArray) {
            HotVideoMode *mode = [HotVideoMode SetModeWithDIC:temp];
            //加载的是旧数据 所有添加到数组的最后面
            [self.modeArray addObject:mode];
        }
        //保存最后的时间截
        Maxtime = [dataDic objectForKey:@"max_time"];
//        NSLog(@"最大时间 %@最小时间%@",Maxtime,MinTime);
        self.tiplable.text = @"加载成功 快滑滑看";
        CATransition *transition = [CATransition animation];
        transition.type = @"cube";//效果类型
        transition.subtype = kCATransitionFromRight;//方向类型 决定动画的开始方向
        transition.duration = 0.4; //单次动画时长
        [self.tiplable.layer addAnimation:transition forKey:@""];
        self.tiplable.hidden = NO;
        [self hiddenTip];
        [self.oneTableView reloadData];
        [self.refreshButton stopAnimating];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    }];
}
//网络错误
- (void)NetWrokErrorFunc{
    self.tiplable.text = @"网络错误 刷新试试";
    self.tiplable.hidden = NO;
}

//隐藏提示
-(void)hiddenTip{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        CATransition *transition = [CATransition animation];
        transition.type = @"cube";//效果类型
        transition.subtype = kCATransitionFromLeft;//方向类型 决定动画的开始方向
        transition.duration = 0.4; //单次动画时长
        [self.tiplable.layer addAnimation:transition forKey:@""];
        self.tiplable.hidden = YES;
    });
}






//计算高度
- (CGFloat)YYHreturnStringHeight:(NSString *)string Width:(CGFloat)Width Font:(int)font{
    
    CGRect frame = [string boundingRectWithSize:CGSizeMake(Width, 10000) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:font] forKey:NSFontAttributeName] context:nil];
    return frame.size.height;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"back" object:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
